namespace SubhadraSolutions.Sharp.Logging.Context
{
    using SubhadraSolutions.Sharp.Logging.Contracts;
    using System;
    using System.Collections.Generic;
    using System.Threading;

    public sealed class ThreadLocalStorageGlobalContextStrategy : IClearableGlobalContextStrategy
    {
        [ThreadStatic]
        private static Dictionary<string, object> _dictionary = null;
        #region Indexers

        public object this[string name]
        {
            get
            {
                if (_dictionary != null && name != null)
                {
                    object o = null;
                    _dictionary.TryGetValue(name, out o);
                    return o;
                }
                return null;
            }
            set
            {
                if (name != null)
                {
                    if (value == null)
                    {
                        if (_dictionary != null)
                        {
                            _dictionary.Remove(name);
                        }
                    }
                    else
                    {
                        if (_dictionary == null)
                        {
                            _dictionary = new Dictionary<string, object>();
                        }
                        _dictionary[name] = value;
                    }
                }
            }
        }

        #endregion Indexers

        #region Methods

        public void Remove(string name)
        {
            this[name] = null;
        }

        #endregion Methods

        public void Clear()
        {
            if (_dictionary != null)
            {
                _dictionary.Clear();
            }
        }
    }
}
